(function($) {
  function Slider(options) {
    this.opt = $.extend({
      gutter: 0,
      navWidth:70
    }, options);
    var t = this;
    var currentIndex = 0;
    var lastIndex = t.opt.element.children().length - t.opt.num;
    var itemWidth = Math.ceil((t.opt.width-(t.opt.num-1) * t.opt.gutter) / t.opt.num);
    var ulWidth = t.opt.element.children().length*(itemWidth+t.opt.gutter);
    
    function _animate(d){
      var _l = -1*currentIndex*(itemWidth+t.opt.gutter);
      t.opt.element.animate({
        left: _l
      });
    }

    function _layout() {
      var el = t.opt.element;
      var $container = $("<div></div>").css({
        width: t.opt.width,
        height: t.opt.height,
        overflow: "hidden",
        position: "relative"
      });
      el.wrap($container);
      el.css({
        width: ulWidth
      });
      
      el.children().css({
        display: "inline-block",
        width: itemWidth,
        marginRight: t.opt.gutter
      });
    }
    _layout();
    return {
      prev: function() {
        if(currentIndex == 0){
          return;
        }
        currentIndex--;
        _animate(-1);
      },
      next: function() {
        if(currentIndex == lastIndex){
          return;
        }
        currentIndex++;
        _animate(1);
      }
    }
  }
  $.fn.hslider = function(options) {
    options = options || {};
    options.element = this;
    var inst = new Slider(options);
    this.data('hslider', inst);
    return this;
  }
})(jQuery);

$(function() {
  var _num = 4;
  _num = global.W < 480 ? 1:_num;
  $('.xiju-gally').hslider({
    width: global.W,
    gutter: 0,
    num: _num
  });

  function _move(d){
    var inst = $('.xiju-gally').data('hslider');
    d > 0 ? inst.next() : inst.prev();
  }

  $('.prev').click(function(){
    _move(-1);
  });
  $('.next').click(function(){
    _move(1);
  });

  if($.browser.mobile){
    $('.xiju').click(function(){
      var $t = $(this);
      if($t.hasClass('active')){
        return true;
      }else{
        $(this).toggleClass('active');
        return false;
      }
    });
  }



});